<template>
  <a-card title="分类管理" :bordered="false">
    <template #extra>
      <a-button v-if="hasPerm('category:manage')" type="primary" @click="openCreate">新建分类</a-button>
    </template>
    <a-table :data-source="list" :loading="loading" row-key="id" :pagination="false">
      <a-table-column title="ID" dataIndex="id" width="80" />
      <a-table-column title="名称" dataIndex="name" />
      <a-table-column title="操作" key="actions" width="160">
        <template #default="{ record }">
          <a-space>
            <a v-if="hasPerm('category:manage')" @click="openEdit(record)">编辑</a>
            <a-popconfirm v-if="hasPerm('category:manage')" title="确定删除该分类？" @confirm="onDelete(record.id)">
              <a-button type="link" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <a-modal v-model:open="modalVisible" :title="editingId ? '编辑分类' : '新建分类'" @ok="onSubmit">
      <a-form layout="vertical">
        <a-form-item label="名称" required>
          <a-input v-model:value="form.name" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item label="描述">
          <a-input v-model:value="form.description" placeholder="描述（可选）" />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { fetchCategories } from '@/api/public/articles'
import { adminCreateCategory, adminUpdateCategory, adminDeleteCategory } from '@/api/admin/modules/categories'
import type { CategoryVO } from '@/types/api'
import { usePerm } from '@/composables/usePerm'

const loading = ref(false)
const list = ref<CategoryVO[]>([])
const modalVisible = ref(false)
const editingId = ref<number | null>(null)
const form = ref<{ name: string; description?: string }>({ name: '' })
const { hasPerm } = usePerm()

async function load() {
  loading.value = true
  try {
    const resp = await fetchCategories()
    list.value = resp.data || []
  } finally { loading.value = false }
}

function openCreate() {
  editingId.value = null
  form.value = { name: '' }
  modalVisible.value = true
}

function openEdit(rec: CategoryVO) {
  editingId.value = rec.id
  form.value = { name: rec.name }
  modalVisible.value = true
}

async function onSubmit() {
  if (!form.value.name || !form.value.name.trim()) return
  if (editingId.value) await adminUpdateCategory(editingId.value, form.value)
  else await adminCreateCategory(form.value)
  modalVisible.value = false
  await load()
}

async function onDelete(id: number) { await adminDeleteCategory(id); await load() }

onMounted(load)
</script>

<style scoped>
</style>


